package com.ry.controller;

import cn.hutool.http.HttpUtil;
import com.alibaba.fastjson.JSONObject;
import com.ry.common.CommonResult;
import com.ry.model.dto.UserDTO;
import com.ry.model.dto.UserRequest;
import com.ry.model.entity.User;
import com.ry.model.entity.WechatProperties;
import com.ry.service.UserService;
import com.ry.utils.ResultUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

/**
 * @author ry
 * @since 2021-11-09 17:20
 **/
@RequestMapping("/user")
@RestController
public class UserController {
    @Autowired
    private UserService userService;

    @Autowired
    private WechatProperties wechatProperties;

    /**
     * 小程序给我code
     * 我拿code去微信接口服务换openId和session_key
     * @return
     */
    @GetMapping("/wechatCall")
    public CommonResult<UserDTO> wechatCall(UserRequest userInfo){
        //使用小程序传过来的code获取openId
        String url = wechatProperties.getCode2SessionUrl(userInfo.getCode());
        String s = HttpUtil.get(url);
        JSONObject jsonObject = JSONObject.parseObject(s);
        String sessionKey = jsonObject.getString("session_key");
        String openId = jsonObject.getString("openid");

        User user = new User();
        user.setNickname(userInfo.getNickName());
        user.setAvatarUrl(userInfo.getAvatarUrl());
        user.setGender(userInfo.getGender());
        user.setOpenId(openId);
        user.setSessionKey(sessionKey);

        //使用openId获取用户信息，小程序和网站应用不同
        //我在这时候已经拿到了用户的信息，在这里就偷懒不做校验了
        UserDTO userDTO = userService.getUserByOpenId(user);
        if (userDTO == null){
            //当前用户为空说明还没有注册
            userDTO = userService.register(user);
        }




        return ResultUtil.success(userDTO);
    }
}
